<?php

/*
 * @copyright :     Ienter asia Technologies
 * @author :        Hunglv
 * @version         v.1.0
 * @created         
 * @Description :   Model Leave Registration
 */
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Mmod_leaveregistration extends MYAD_Model {

    protected $table_name = 'm_leaveregistration';
    protected $table_leavetype = 'm_leavetype';
    protected $table_employee = 'm_employee';
    protected $table_leaveregistration = 'm_leaveregistration';

    function __construct() {
        parent::__construct();
        $this->load->library('form_validation');
    }

    /*
     * @author :        Hunglv
     * @created:        
     * @Description:    Get all data for view of Leave registration list
     * @Input :         $page = 0;
     * @Output :        (Array) data for view data
     */

    function getAllData($page = 0) {
        $arrayData = array();
        $arraySearch = array();
        if (isset($_POST['txtKeyword']) && $_POST['txtKeyword'] != '') {
            $arrayData = array(
                'c.EmployeeName' => dQuotes($this->input->post('txtKeyword')),
            );
            $arraySearch = array(
                'txtKeyword' => dQuotes($this->input->post('txtKeyword')),
            );
        }
        $allLeave = $this->getLeaveRegistrationData($arrayData);
        /* load pagination */
        $pagiData = array(
            'base_url' => base_url('leaveregistration/'),
            'total_rows' => count($allLeave['data']),
        );
        $pagination = $this->config->item('pagination');
        $offset = isset($pagiData['per_page']) ? $pagiData['per_page'] : $pagination['per_page'];
        $pagi = $this->getPagination($pagiData);
        $data = array(
            'show' => 'index',
            'js' => array('jquery-ui.js'),
            'css' => array('jquery-ui.css'),
            'pagi' => $pagi,
            'order' => $page,
            'title' => $this->lang->line('LR_title'),
        );
        /* load conversion */
        $leaveData = $this->getLeaveRegistrationData($arrayData, $page, $offset, array());
        return array_merge($data, $leaveData, $arraySearch);
    }

    /*
     * @author :        Hunglv
     * @created:        
     * @Description:    add Leave registration Data
     * @Input :         
     * @Output :        
     */

    function newLeaveregistrationData() {
        $temp = array();
        $data = array(
            'LeaveTypeId' => $this->input->post('cboLeavetype'),
            'EmployeeId' => $this->input->post('hidEmployeeId'),
            'StartDate' => $this->input->post('txtStartDate'),
            'EndDate' => $this->input->post('txtEndDate'),
            'StartTime' => $this->input->post('txtStartTime'),
            'EndTime' => $this->input->post('txtEndTime'),          
        );
        /* BEGIN Quyet Add 29/7/2014 */
        $dataCondition = $data;
        $dataCondition['RegistrationId'] = 0;
        $result = $this->duplicateDateTime($dataCondition);
        if ($result) {
            $temp['flag'] = FALSE;
            $temp['message'] = $this->lang->line('LR_updateDB_duplicate');
            return $temp;
        }
        /* END Quyet Add 29/7/2014 */

        $result = $this->updateDB($this->table_name,$data);
        if ($result == TRUE) {
            $temp['flag'] = TRUE;
            $temp['message'] = $this->lang->line('LR_updateDB_success');
        } else {
            $temp['flag'] = FALSE;
            $temp['message'] = $this->lang->line('LR_updateDB_fall');
        }
        return $temp;
    }

    /*
     * @author :        Hunglv
     * @created:        
     * @Description:    add Leave registration Data
     * @Input :         
     * @Output :        
     */

    function updateLeaveregistrationData() {
        $temp = array();
        $data = array(
            'LeaveTypeId' => $this->input->post('cboLeavetype'),
            'EmployeeId' => $this->input->post('hidEmployeeId'),
            'StartDate' => $this->input->post('txtStartDate'),
            'EndDate' => $this->input->post('txtEndDate'),
            'StartTime' => $this->input->post('txtStartTime'),
            'EndTime' => $this->input->post('txtEndTime'),          
            'Del_Flag' => $this->input->post('chkDelFlag'),          
        );
        $id = $this->input->post('hidLeaveId');
        /* BEGIN Quyet Add 29/7/2014 */
        $dataCondition = $data;
        $dataCondition['RegistrationId'] = $id;
        $result = $this->duplicateDateTime($dataCondition);
        if ($result) {
            $temp['flag'] = FALSE;
            $temp['data'] = $data;
            $temp['message'] = $this->lang->line('LR_updateDB_duplicate');
            return $temp;
        }
        /* END Quyet Add 29/7/2014 */
        $result = $this->updateDB($this->table_name,$data,array("RegistrationId"=>$id));
        if ($result == TRUE) {
            $temp['flag'] = TRUE;
            $temp['data'] = $data;
            $temp['message'] = $this->lang->line('LR_updateDB_success');
        } else {
            $temp['flag'] = FALSE;
            $temp['data'] = $data;
            $temp['message'] = $this->lang->line('LR_updateDB_fall');
        }
        return $temp;
    }

    /*
     * @author :        HungLV
     * @Description:    Get Leave Registration data
     * @Input :         
     *                  (Integer) $limit
     *                  (Integer) $offset
     * @Output :        Array data
     */

    function getLeaveRegistrationData($arrayData, $limit = Null, $offset = Null) {
        $this->db->from($this->table_name.' as a ');
        $this->db->join($this->table_leavetype.' as b ', 'b.LeaveTypeId = a.LeaveTypeId');
        $this->db->join($this->table_employee.' as c ', 'c.EmployeeId = a.EmployeeId');
        $this->db->select('a.Del_Flag,a.RegistrationId,a.LeaveTypeId,a.EmployeeId,a.StartDate,a.EndDate,a.StartTime,a.EndTime,c.EmployeeName,b.LeaveTypeName,b.IsPaidLeave');
        $this->db->where('c.CompanyCode',$this->session->userdata('CompanyCode'));
        if (count($arrayData)) {
            $this->db->like($arrayData);
        }
        if ($limit !== Null && $offset !== Null) {
            $this->db->limit($offset, $limit);
        } elseif ($limit !== NULL) {
            $this->db->limit($limit);
        }
        $query = $this->db->get();
        $result = $query->result_array();
        return array('data' => $result);
    }

    /*
     * @author :        HungLV
     * @Description:    Get all data employee
     * @Input :         
     *                  $EmployeeId = ""
     * @Output :        Array data
     */

    function allEmployee($page) {
        // create session data
        $this->session->set_userdata('cboLeavetype', $this->input->post('cboLeavetype'));
        $this->session->set_userdata('txtStartDate', $this->input->post('txtStartDate'));
        $this->session->set_userdata('txtEndDate', $this->input->post('txtEndDate'));
        $this->session->set_userdata('txtStartTime', $this->input->post('txtStartTime'));
        $this->session->set_userdata('txtEndTime', $this->input->post('txtEndTime'));       
        // config pagination
        $employeeData = $this->loadDataEmployee();
        /* load pagination */
        $pagiData = array(
            'base_url' => base_url('leaveregistration/listemployee'),
            'total_rows' => count($employeeData['data']),
            'uri_segment' => 3,
        );
        $pagination = $this->config->item('pagination');
        $offset = isset($pagiData['per_page']) ? $pagiData['per_page'] : $pagination['per_page'];
        $pagi = $this->getPagination($pagiData);
        $temp = array(
            'leaveID'=>$this->input->post('hidLeaveId'),
            'segment'=>$this->input->post('hidSegment'),
            'employeeId'=>$this->input->post('hidEmployeeId'),
            'pagi' => $pagi,
            'order' => $page,
            'show' => 'searchlistemployee',
            'title' => $this->lang->line('LR_SearchList'),
        );
        
        $data = $this->loadDataEmployee($page, $offset);
        return array_merge($data, $temp);
    }

    /*
     * @author :        HungLV
     * @Description:    get all data employee
     * @Input :         
     * @Output :        Return Array data
     */

    function loadDataEmployee($limit = Null, $offset = Null){
        $this->db->select('EmployeeId,EmployeeName,DateOfBirth,IdCardNumber,Email');
        $this->db->where('CompanyCode',$this->session->userdata('CompanyCode'));
        if ($limit !== Null && $offset !== Null) {
            $this->db->limit($offset, $limit);
        } elseif ($limit !== NULL) {
            $this->db->limit($limit);
        }        
        $query = $this->db->get($this->table_employee);
        $result = $query->result_array();
        return array('data' => $result);
    }

    /*
     * @author :        HungLV
     * @Description:    get all id employee by name
     * @Input :         $employeeID
     * @Output :        Return Array data
     */

    function loadEmployeeId($employeeID) {
        $this->db->from($this->table_employee.' as a ');
        $this->db->like('a.EmployeeId', $employeeID);
        $this->db->like('a.CompanyCode',$this->session->userdata('CompanyCode'));
        $query = $this->db->get();
        return $query->row_array();
    }

    /*
     * @author :        HungLV
     * @Description:    get data by id
     * @Input :         $name = ""
     * @Output :        Return Array data for view
     */

    function getLeaveRegistrationByID($RegistrationId) {
        $this->db->from($this->table_name.' as a ');
        $this->db->join($this->table_leavetype.' as b ', 'b.LeaveTypeId = a.LeaveTypeId');
        $this->db->join($this->table_employee.' as c ', 'c.EmployeeId = a.EmployeeId');
        $this->db->select('a.RegistrationId,a.LeaveTypeId,a.EmployeeId,a.StartDate,a.EndDate,a.StartTime,a.EndTime,a.Del_Flag,c.EmployeeName,b.LeaveTypeName,b.IsPaidLeave');
        $this->db->where('c.CompanyCode',$this->session->userdata('CompanyCode'));
        $this->db->where('RegistrationId', $RegistrationId);
        $query = $this->db->get();
        return $query->row_array();
    }

    /*
     * @author :        HungLV
     * @Description:    Validate input data
     * @Input :         Null
     * @Output :        
     */

    function validateInput() {
        $_POST['txtEmployee'] = mb_convert_kana($_POST['txtEmployee'], 'a');
        $_POST['txtStartDate'] = mb_convert_kana($_POST['txtStartDate'], 'a');
        $_POST['txtEndDate'] = mb_convert_kana($_POST['txtEndDate'], 'a');
        $_POST['txtStartTime'] = mb_convert_kana($_POST['txtStartTime'], 'a');
        $_POST['txtEndTime'] = mb_convert_kana($_POST['txtEndTime'], 'a');
        $this->form_validation->set_error_delimiters('', '');
        $this->form_validation->set_rules('id', 'id', 'integer');
        $this->form_validation->set_rules('txtEmployee', $this->lang->line('LR_Employee'), 'required');
        $this->form_validation->set_rules('cboLeavetype', $this->lang->line('LR_LeaveType'), 'required|callback_validate_select');
        $this->form_validation->set_rules('txtStartDate', $this->lang->line('LR_StartDate'), 'required|callback_validate_date');
        $this->form_validation->set_rules('txtEndDate', $this->lang->line('LR_EndDate'), 'required|callback_validate_date|callback_lessThanOrEqualDate[txtStartDate]');
        $this->form_validation->set_rules('txtStartTime', $this->lang->line('LR_StartTime'), 'required|callback_validate_time');
        $this->form_validation->set_rules('txtEndTime', $this->lang->line('LR_EndTime'), 'required|callback_validate_time|callback_validate_timeend[txtStartTime]');
        return $this->form_validation->run();
    }

    /*
     * @author :        HungLV
     * @Description:    get setup info for view
     * @Input :         Null
     * @Output :        Return Array for view
     */

    function getInfoLeaveregistration() {
        $data = array(
            'title' => $this->lang->line('LR_LeaveRegistration'),
            'js' => array('jquery-ui.js'),
            'css' => array('jquery-ui.css'),
            'show' => 'addleaveregistration',
        );
        if (isset($_POST['btnSubmit'])) {
            /* is load default */
            $emp = array(
                'txtEmployee' => $this->input->post('txtEmployee'),             
                'cboLeavetype' => $this->input->post('cboLeavetype'),             
                'txtStartDate' => $this->input->post('txtStartDate'),             
                'txtEndDate' => $this->input->post('txtEndDate'),             
                'txtStartTime' => $this->input->post('txtStartTime'),            
                'txtEndTime' => $this->input->post('txtEndTime'),
            );
        } else {
            $emp = array(
                'txtEmployee' => set_value('txtEmployee'),             
                'cboLeavetype' => $this->session->userdata('cboLeavetype')!=''?$this->session->userdata('cboLeavetype'):set_value('cboLeavetype'),         
                'txtStartDate' => $this->session->userdata('txtStartDate')?$this->session->userdata('txtStartDate'):set_value('txtStartDate'),         
                'txtEndDate' => $this->session->userdata('txtEndDate')?$this->session->userdata('txtEndDate'):set_value('txtEndDate'),         
                'txtStartTime' => $this->session->userdata('txtStartTime')?$this->session->userdata('txtStartTime'):set_value('txtStartTime'),         
                'txtEndTime' => $this->session->userdata('txtEndTime')?$this->session->userdata('txtEndTime'):set_value('txtEndTime'),                            
            );
        }        
        return array_merge($data,$emp);
    }

    /*
     * @author :        HungLV
     * @Description:    get setup info for view
     * @Input :         Null
     * @Output :        Return Array for view
     */

    function getInfoEditLeaveregistration($leaveType,$employeeID) {
        $data = array(
            'title' => $this->lang->line('LR_LeaveRegistration'),
            'js' => array('jquery-ui.js'),
            'css' => array('jquery-ui.css'),
            'show' => 'editleaveregistration',
        );
        if (isset($_POST['btnSubmit'])) {
            /* is load default */
            $emp = array(
                'txtEmployee'       => $this->input->post('txtEmployee'),             
                'idEmployee'        => $this->input->post('idEmployee'),             
                'cboLeavetype'      => $this->input->post('cboLeavetype'),             
                'txtStartDate'      => $this->input->post('txtStartDate'),             
                'txtEndDate'        => $this->input->post('txtEndDate'),             
                'txtStartTime'      => $this->input->post('txtStartTime'),            
                'txtEndTime'        => $this->input->post('txtEndTime'),            
                'RegistrationId'    => $this->input->post('hidLeaveId'),            
                'chkDelFlag'        => $this->input->post('chkDelFlag'),            
            );
        }
        else{
            if(count($leaveType)>0){
                $employeeInfo = $this->getInfoEmployeeID($employeeID);
                $emp = array(
                    'txtEmployee' => $employeeInfo['EmployeeName'],       
                    'idEmployee' => $employeeInfo['EmployeeId'],       
                    'RegistrationId' => $leaveType['RegistrationId'],              
                    'cboLeavetype' => $this->session->userdata('cboLeavetype')!=''?$this->session->userdata('cboLeavetype'):$leaveType['LeaveTypeId'],         
                    'txtStartDate' => $this->session->userdata('txtStartDate')?$this->session->userdata('txtStartDate'):date('Y/m/d',strtotime($leaveType['StartDate'])),         
                    'txtEndDate' => $this->session->userdata('txtEndDate')?$this->session->userdata('txtEndDate'):date('Y/m/d',strtotime($leaveType['EndDate'])),         
                    'txtStartTime' => $this->session->userdata('txtStartTime')?$this->session->userdata('txtStartTime'):date('G:i',strtotime($leaveType['StartTime'])),         
                    'txtEndTime' => $this->session->userdata('txtEndTime')?$this->session->userdata('txtEndTime'):date('G:i',strtotime($leaveType['EndTime'])),                           
                    'chkDelFlag' => $this->session->userdata('chkDelFlag')!=''?$this->session->userdata('chkDelFlag'):$leaveType['Del_Flag'],                           
                );                  
            }
            else {
                $emp = array(
                    'txtEmployee' => set_value('txtEmployee'), 
                    'idEmployee' => $this->input->post('idEmployee'),
                    'RegistrationId' => $this->input->post('hidLeaveId'),
                    'cboLeavetype' => $this->session->userdata('cboLeavetype')!=''?$this->session->userdata('cboLeavetype'):set_value('cboLeavetype'),         
                    'txtStartDate' => $this->session->userdata('txtStartDate')?$this->session->userdata('txtStartDate'):set_value('txtStartDate'),         
                    'txtEndDate' => $this->session->userdata('txtEndDate')?$this->session->userdata('txtEndDate'):set_value('txtEndDate'),         
                    'txtStartTime' => $this->session->userdata('txtStartTime')?$this->session->userdata('txtStartTime'):set_value('txtStartTime'),         
                    'txtEndTime' => $this->session->userdata('txtEndTime')?$this->session->userdata('txtEndTime'):set_value('txtEndTime'),                           
                    'chkDelFlag' => $this->session->userdata('chkDelFlag')!=''?$this->session->userdata('chkDelFlag'):$this->input->post('chkDelFlag'),                           
                );
            }             
        }        
        return array_merge($data,$emp);
    }

    /*
     * @author :        HungLV
     * @Description:    check exist id leaveregistration
     * @Input :         (Number) $id
     * @Output :        Return true or false
     */

    function checkIdLeaveRegistration($id) {
        $this->db->where('RegistrationId', $id);
        $query = $this->db->get($this->table_name);
        if ($query->num_rows() > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
    /*
     * @author :        HungLV
     * @Description:    check exist employee id 
     * @Input :         (Number) $id
     * @Output :        Return true or false
     */

    function checkEmployeeId($id) {
        $this->db->where('EmployeeId', $id);
        $this->db->where('CompanyCode', $this->session->userdata('CompanyCode'));
        $query = $this->db->get($this->table_employee);
        if ($query->num_rows() > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
    /*
     * @author :        HungLV
     * @Description:    return all data when submit
     * @Input :         
     * @Output :        Return array
     */

    function getPostLeaveRegistration() {
        $data = array(
            'LeaveTypeId' => $this->input->post('cboLeavetype'),
            'EmployeeId' => $this->input->post('idEmployee'),
            'StartDate' => $this->input->post('txtStartDate'),
            'EndDate' => $this->input->post('txtEndDate'),
            'StartTime' => $this->input->post('txtStartTime'),
            'EndTime' => $this->input->post('txtEndTime'),
        );
        return $data;
    }
    /*
     * @author :        HungLV
     * @Description:    return employee info by id
     * @Input :         $idemployee
     * @Output :        Return array
     */

    function getInfoEmployeeID($idemployee) {
        $this->db->where('EmployeeId',$idemployee);
        $this->db->where('CompanyCode',$this->session->userdata('CompanyCode'));
        $query = $this->db->get($this->table_employee);
        return $query->row_array();
    }
    /*
     * @copyright :     Ienter asia Technologies
     * @author :        Quyet
     * @version         v.1.0
     * @created         29/7/2014
     * @Description :   return true if duplicate
     */

    function duplicateDateTime($data = array()) {
        $temp = FALSE;
        if (count($data)) {
            $registrationId = isset($data['RegistrationId']) ? $data['RegistrationId'] : 0;
            $employeeId = isset($data['EmployeeId']) ? $data['EmployeeId'] : 0;
            //set start time --> end time
            $startDate = strtotime($data['StartDate'] . ' ' . $data['StartTime'] . ':00');
            $endDate = strtotime($data['EndDate'] . ' ' . $data['EndTime'] . ':00');
            if ($registrationId) {
                //is update
                $condition = array(
                    'RegistrationId !=' => (integer) $registrationId,
                    'EmployeeId' => (integer) $employeeId,
                    'Del_Flag' => 0,
                );
            } else {
                // is insert
                $condition = array(
                    'EmployeeId' => (integer) $employeeId,
                    'Del_Flag' => 0,
                );
            }
            $query = $this->db->get_where($this->table_leaveregistration, $condition);
            $result = $query->result();
            if (count($result)) {
                foreach ($result as $item) {
                    $tempStart = strtotime($item->StartDate . ' ' . $item->StartTime);
                    $tempEnd = strtotime($item->EndDate . ' ' . $item->EndTime);
                    if (!($endDate <= $tempStart || $startDate >= $tempEnd)) {
                        $temp = TRUE;
                        break;
                    }
                }
            }
        }
        return $temp;
    }
    /*
     * @author :        HungLV
     * @Description:    Unset sesion data
     * @Input :         Null
     * @Output :        Null
     */

    function unsetDataSession() {
        $this->session->unset_userdata('cboLeavetype');
        $this->session->unset_userdata('txtStartDate');
        $this->session->unset_userdata('txtEndDate');
        $this->session->unset_userdata('txtStartTime');
        $this->session->unset_userdata('txtEndTime');        
        $this->session->unset_userdata('chkDelFlag');        
    }
    /*
     * @author :        HungLV
     * @Description:    Unset sesion data
     * @Input :         Null
     * @Output :        Null
     */

    function getAllLeaveType() {
        $this->db->where('CompanyCode',$this->session->userdata('CompanyCode'));
        $query = $this->db->get($this->table_leavetype);
        return $query->result_array();
    }
}

?>